import Application from './Application'
import Screen from './Screen'
import Transition from './Transition'

export default class History {
  /**
   * 当前的场景
   */
  currentScreen?: Screen
  /**
   * 所有的历史场景
   */
  screens: Screen[]
  // 应用
  application: Application
  // 过渡效果
  transition?: Transition

  /**
   * 追加场景
   * @param screen 场景
   */
  async pushScreen(screen: Screen, transition?: Transition) {
    if(screen == this.currentScreen) return
    screen.application = this.application
    this.transition = transition
    if(transition) {
      transition.initProgress =  1
      if(this.currentScreen) {
        transition.initProgress = 0
        transition.setPrevScreen(this.currentScreen)
      }
      transition.setNextScreen(screen)
      transition.onComplete(() => {
        this.currentScreen = screen
        this.transition = null
        transition = null
      })
      await screen.init()
      await screen.load()
      transition.start()
      return
    }


    if(this.currentScreen) {
      await this.currentScreen.unload()
      this.screens.push(this.currentScreen)
    }
    await screen.init()
    await screen.load()
    this.currentScreen = screen
  }
  /**
   * 返回上一个场景
   */
  async popScreen() {
    this.currentScreen.destroy()
    var historyScreen = this.screens.pop()
    if(historyScreen) {
      await historyScreen.load()
      this.currentScreen = historyScreen
    }
  }
  /**
   * 重置当前场景
   * @param screen 场景
   */
  async resetScreen(screen: Screen) {
    if(screen == this.currentScreen) return
    await this.currentScreen.unload()
    screen.application = this.application
    this.currentScreen = screen
    await screen.init()
    await screen.load()
  }
  /**
   * 回退场景
   * @param screen 场景
   */
  backToScreen(screen: Screen) {
    var index = this.screens.findIndex((historyScreen) => historyScreen === screen)
    if(index !== -1) {
      var deletedScreen = this.screens.splice(index, this.screens.length - index + 1)
      deletedScreen.forEach((item) => {
        item.destroy()
      })
    }
  }
}